package com.eslserver.action.image;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.aware.ESLAware;
import com.eslserver.core.config.AttachmentConfig;
import com.eslserver.dao.ESLDAO;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.dao.ImageDAO;
import com.eslserver.to.ESL;
import com.eslserver.to.Image;
import com.eslserver.to.wrapper.ImageWrapper;
import com.eslserver.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet implements ESLAware {
	public static final Logger LOG = LoggerFactory
			.getLogger(FileUploadServlet.class);

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		writer.write("call POST with multipart form data");
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		if (!ServletFileUpload.isMultipartContent(req)) {
			throw new IllegalArgumentException(
					"Request is not multipart, please 'multipart/form-data' enctype for your form.");
		}

		ServletFileUpload uploadHandler = new ServletFileUpload(
				new DiskFileItemFactory());
		PrintWriter writer = resp.getWriter();
		resp.setContentType("text/plain");
		try {
			String eslID = null;
			String systemPath = null;
			Date now = new Date();

			@SuppressWarnings("unchecked")
			List<FileItem> items = uploadHandler.parseRequest(req);

			for (FileItem item : items) {
				if (item.isFormField()) {
					if (item.getFieldName().equals(HIDDEN_ESLID)) {
						eslID = item.getString();
					}
				}
			}

			for (FileItem item : items) {
				if (!item.isFormField()) {
					File dir = new File(AttachmentConfig.tomcatPath
							+ AttachmentConfig.contextPath + "\\" + eslID
							+ "\\" + now.getTime());
					if (!dir.exists()) {
						dir.mkdirs();
					}

					File file = new File(dir, item.getName());
					item.write(file);
					systemPath = file.getPath();
					break; // assume we only get one file at a time
				}
			}

			ImageDAO eslImageDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getImageDAO();
			ESLDAO eslDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getESLDAO();

			Image image = Image.createImage();
			image.setSystemPath(systemPath);
			image.setCreateDate(now);
			image.setModifyDate(now);
			image.setDelete(false);
			eslImageDAO.addImage(image);

			ESL esl = eslDAO.loadESL(Integer.valueOf(eslID));
			esl.getImages().add(image);
			eslDAO.updateESL(esl);

			ImageWrapper imageWrapper = ImageWrapper
					.createESLImageWrapper(image);
			writer.write(JSONResponseUtil.getJSONObjectString(imageWrapper));
		} catch (FileUploadException e) {
			LOG.error("Error uploading file.", e);
		} catch (Exception e) {
			LOG.error("Error writing file to disk.", e);
		} finally {
			writer.close();
		}
	}
}
